#Boa:Frame:Frame1

import wx
import wx.grid
import utiles
import consultasBD
from decimal import Decimal

ROJO = (255, 145, 145, 255)
VERDE = (145, 255, 145, 255)
AZUL = (145, 145, 255, 255)
BLANCO = (255, 255, 255, 255)
AMARILLO = (254, 248, 191, 255)
GRIS = ( 220, 220, 220, 255)
NEGRO = ( 0, 0, 0, 255)
VERDENEGRO = ( 47, 79, 79, 255)

def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3, 
 wxID_FRAME1BUTTON4, wxID_FRAME1CHECKBOX1, wxID_FRAME1CHECKBOX2, 
 wxID_FRAME1COMBOBOX1, wxID_FRAME1COMBOBOX2, wxID_FRAME1DATEPICKERCTRL1, 
 wxID_FRAME1DATEPICKERCTRL2, wxID_FRAME1GRID1, wxID_FRAME1PANEL1, 
 wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2, wxID_FRAME1STATICTEXT3, 
 wxID_FRAME1STATICTEXT4, wxID_FRAME1STATICTEXT5, wxID_FRAME1STATICTEXT6, 
 wxID_FRAME1STATICTEXT8, wxID_FRAME1TEXTCTRL1, wxID_FRAME1TEXTCTRL2, 
 wxID_FRAME1TEXTCTRL3, 
] = [wx.NewId() for _init_ctrls in range(23)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(369, 120), size=wx.Size(903, 468),
              style=wx.DEFAULT_FRAME_STYLE, title='Reporte de Ventas')
        self.SetClientSize(wx.Size(895, 441))

        self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(895, 441),
              style=wx.TAB_TRAVERSAL)

        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label='Sucursal', name='staticText1', parent=self.panel1,
              pos=wx.Point(8, 8), size=wx.Size(40, 13), style=0)

        self.comboBox1 = wx.ComboBox(choices=[], id=wxID_FRAME1COMBOBOX1,
              name='comboBox1', parent=self.panel1, pos=wx.Point(8, 24),
              size=wx.Size(130, 21), style=0, value='')
        self.comboBox1.SetLabel('')

        self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
              label='desde', name='staticText2', parent=self.panel1,
              pos=wx.Point(144, 8), size=wx.Size(29, 13), style=0)

        self.datePickerCtrl1 = wx.DatePickerCtrl(id=wxID_FRAME1DATEPICKERCTRL1,
              name='datePickerCtrl1', parent=self.panel1, pos=wx.Point(144, 24),
              size=wx.Size(80, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.datePickerCtrl2 = wx.DatePickerCtrl(id=wxID_FRAME1DATEPICKERCTRL2,
              name='datePickerCtrl2', parent=self.panel1, pos=wx.Point(224, 24),
              size=wx.Size(80, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,
              label='hasta', name='staticText3', parent=self.panel1,
              pos=wx.Point(224, 8), size=wx.Size(27, 13), style=0)

        self.checkBox1 = wx.CheckBox(id=wxID_FRAME1CHECKBOX1, label='tipo 1',
              name='checkBox1', parent=self.panel1, pos=wx.Point(320, 16),
              size=wx.Size(56, 13), style=0)
        self.checkBox1.SetValue(True)

        self.checkBox2 = wx.CheckBox(id=wxID_FRAME1CHECKBOX2, label='tipo 2',
              name='checkBox2', parent=self.panel1, pos=wx.Point(320, 32),
              size=wx.Size(56, 13), style=0)
        self.checkBox2.SetValue(False)

        self.staticText4 = wx.StaticText(id=wxID_FRAME1STATICTEXT4,
              label='Tipo de reporte', name='staticText4', parent=self.panel1,
              pos=wx.Point(392, 8), size=wx.Size(74, 13), style=0)

        self.comboBox2 = wx.ComboBox(choices=[], id=wxID_FRAME1COMBOBOX2,
              name='comboBox2', parent=self.panel1, pos=wx.Point(392, 24),
              size=wx.Size(176, 21), style=0, value='')
        self.comboBox2.SetLabel('')

        self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL1, name='textCtrl1',
              parent=self.panel1, pos=wx.Point(392, 64), size=wx.Size(24, 21),
              style=0, value='')
        self.textCtrl1.SetEditable(False)

        self.textCtrl2 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL2, name='textCtrl2',
              parent=self.panel1, pos=wx.Point(456, 64), size=wx.Size(24, 21),
              style=0, value='')
        self.textCtrl2.Bind(wx.EVT_KILL_FOCUS, self.OnKillFeriados)

        self.textCtrl3 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL3, name='textCtrl3',
              parent=self.panel1, pos=wx.Point(512, 64), size=wx.Size(24, 21),
              style=0, value='')

        self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='Procesar',
              name='button1', parent=self.panel1, pos=wx.Point(576, 24),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnProcesar, id=wxID_FRAME1BUTTON1)

        self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='Limpiar',
              name='button2', parent=self.panel1, pos=wx.Point(656, 24),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnLimpiar, id=wxID_FRAME1BUTTON2)

        self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Imprimir',
              name='button3', parent=self.panel1, pos=wx.Point(736, 24),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnImprimir, id=wxID_FRAME1BUTTON3)

        self.button4 = wx.Button(id=wxID_FRAME1BUTTON4, label='Salir',
              name='button4', parent=self.panel1, pos=wx.Point(816, 24),
              size=wx.Size(75, 23), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_FRAME1BUTTON4)

        self.grid1 = wx.grid.Grid(id=wxID_FRAME1GRID1, name='grid1',
              parent=self.panel1, pos=wx.Point(8, 88), size=wx.Size(880, 344),
              style=0)

        self.staticText5 = wx.StaticText(id=wxID_FRAME1STATICTEXT5,
              label='Dias habiles', name='staticText5', parent=self.panel1,
              pos=wx.Point(392, 48), size=wx.Size(56, 13), style=0)

        self.staticText6 = wx.StaticText(id=wxID_FRAME1STATICTEXT6,
              label='Feriados', name='staticText6', parent=self.panel1,
              pos=wx.Point(456, 48), size=wx.Size(41, 13), style=0)

        self.staticText8 = wx.StaticText(id=wxID_FRAME1STATICTEXT8,
              label='Pendientes', name='staticText8', parent=self.panel1,
              pos=wx.Point(512, 48), size=wx.Size(53, 13), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)
        fecha1 = str(utiles.getDaysExtreme()[0])
        utiles.cargar_fecha(fecha1,self.datePickerCtrl1)
        self.cargarSucursales()
        self.cargarTipoReporte()
        self.crearGrilla()
        self.comboBox1.SetFocus()
        feriados,totaldias,pendientes = utiles.getTotalDias("domingo")
        self.textCtrl1.SetLabel(str(totaldias-feriados))
        self.textCtrl3.SetLabel(str(pendientes))

    def OnKillFeriados(self, event):
        try:
            valor = int(self.textCtrl2.GetLabel())
        except:
            valor = 0
        totaldias = int(self.textCtrl1.GetLabel())
        totaldias = totaldias-valor
        self.textCtrl1.SetLabel(str(totaldias))

    def limpiarGrilla(self):
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        for col in xrange(self.grid1.GetNumberCols()):
            self.grid1.DeleteCols()
        self.grid1.AppendCols()
        self.grid1.SetColLabelValue(0,' ')

    def OnLimpiar(self, event):
        self.limpiarGrilla()
        self.comboBox1.SetSelection(-1)
        self.comboBox2.SetSelection(-1)
        self.comboBox1.SetFocus()

    def cargarSucursales(self):
        SQL = "SELECT nombre FROM sucursales"
        resultado = consultasBD.ordenCrudaDict(SQL)
        for item in resultado:
            self.comboBox1.Append(item["nombre"])
        self.comboBox1.Append("TODAS")
        self.comboBox1.SetEditable(False)

    def cargarTipoReporte(self):
        self.comboBox2.Append("Ventas, N.C., Devoluciones")
        self.comboBox2.Append("Ventas 1, 2 y comisiones")
        self.comboBox2.Append("Ventas segun medios de pagos")
        self.comboBox2.Append("Listado de IVA")
        self.comboBox2.SetSelection(-1)
        self.comboBox2.SetEditable(False)

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def crearGrilla(self):
        columnas = [' ']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)

        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        self.grid1.EnableEditing(False)
        self.grid1.Refresh()

    def OnSalir(self, event):
        self.Close()

    def verificarOpciones(self):
        if self.comboBox1.GetSelection()<0:
            utiles.mensaje(None,"Debe indicar sucursal")
            self.comboBox1.SetFocus()
            return False
        if not self.checkBox1.GetValue() and not self.checkBox2.GetValue():
            utiles.mensaje(None,"Debe indicar algun tipo de venta")
            self.checkBox1.SetFocus()
            return False
        if self.comboBox2.GetSelection()<0:
            utiles.mensaje(None,"Debe indicar Tipo de Reporte")
            self.comboBox2.SetFocus()
            return False
        return True

    def rangoFecha(self):
        fecha1 = self.datePickerCtrl1.GetLabel()
        fecha1 = fecha1.replace("/","-")
        fecha1 = utiles.invertirFecha(fecha1)
        fecha2 = self.datePickerCtrl2.GetLabel()
        fecha2 = fecha2.replace("/","-")
        fecha2 = utiles.invertirFecha(fecha2)
        return fecha1,fecha2

    def armarSQL1(self,sucursal=0):
        #obteniendo NC - detalle
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"
                    
        r1 = "SELECT v.fecha, v.idventa, v.nrofactura, v.idcliente, \n"
        r2 = "       v.idformaticket, v.totalfactura, v.sucursal, v.descuento, \n"
        r3 = "       v.iva, v.totalsiniva, vtp.ptc, ptc.codsussan, ptc.talle, \n"
        r4 = "       ptc.color, vtp.descri, vtp.cantidad, vtp.preciolista, \n"
        r5 = "       vtp.descuento, vtp.preciofinal, vtp.devuelto \n"
        r6 = "FROM ventas v, ventastieneproductos vtp, producto_talle_color ptc \n"
        r7 = "WHERE v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' \n"
        r8 = "      AND v.nrofactura=vtp.nrofactura "+opcion1
        r9 = "      AND v.idventa=vtp.idticket AND vtp.ptc=ptc.id \n"
        r0 = "      AND vtp.devuelto='1' \n"
        rA = "ORDER BY v.fecha, v.idventa, v.nrofactura "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        return datos

    def armarSQL2(self,sucursal):
        #obteniendo Ventas - detalle
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"

        r1 = "SELECT v.fecha, v.idventa, v.nrofactura, v.idcliente, \n"
        r2 = "       v.idformaticket, v.totalfactura, v.sucursal, \n"
        r3 = "       v.descuento, v.iva, v.totalsiniva, vtp.ptc, \n"
        r4 = "       ptc.codsussan, ptc.talle, ptc.color, vtp.descri, \n"
        r5 = "       vtp.cantidad, vtp.preciolista, vtp.descuento, \n"
        r6 = "       vtp.preciofinal, vtp.devuelto \n"
        r7 = "FROM ventas v, ventastieneproductos vtp, producto_talle_color ptc \n"
        r8 = "WHERE v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' \n"
        r9 = "      AND v.nrofactura=vtp.nrofactura AND v.idventa=vtp.idticket \n"
        r0 = "      AND vtp.ptc=ptc.id AND vtp.devuelto<>'1' \n"
        rA = "      AND vtp.cantidad>0 \n"
        rB = "ORDER BY v.fecha, v.idventa, v.nrofactura "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        return datos

    def armarSQL3(self,sucursal):
        #obteniendo Devoluciones - detalle
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"

        r1 = "SELECT v.fecha, v.idventa, v.nrofactura, v.idcliente, \n"
        r2 = "       v.idformaticket, v.totalfactura, v.sucursal, \n"
        r3 = "       v.descuento, v.iva, v.totalsiniva, vtp.ptc, \n"
        r4 = "       ptc.codsussan, ptc.talle, ptc.color, vtp.descri, \n"
        r5 = "       vtp.cantidad, vtp.preciolista, vtp.descuento, \n"
        r6 = "       vtp.preciofinal, vtp.devuelto \n"
        r7 = "FROM ventas v, ventastieneproductos vtp, producto_talle_color ptc \n"
        r8 = "WHERE v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' \n"
        r9 = "      AND v.nrofactura=vtp.nrofactura AND v.idventa=vtp.idticket \n"
        r0 = "      AND vtp.ptc=ptc.id AND vtp.devuelto<>'1' \n"
        rA = "      AND vtp.cantidad<0 \n"
        rB = "ORDER BY v.fecha, v.idventa, v.nrofactura "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        print sql
        return datos

    def armarSQL4(self,sucursal):
        #obteniendo NC - totales
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"
        opcion2 = " AND v.sucursal='"+str(sucursal+1)+"' "
        opcion3 = " AND v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' "

        r1 = "SELECT v.sucursal,SUM(vtp.preciofinal) AS total,\n"
        r2 = "       (SUM(vtp.preciofinal)/1.21) AS iva,\n"
        r3 = "       (SUM(vtp.preciofinal)-SUM(vtp.preciofinal)/1.21) AS subtotal \n"
        r4 = "FROM ventas v, ventastieneproductos vtp, \n"
        r5 = "     (SELECT v.idventa, v.nrofactura \n"
        r6 = "      FROM ventas v, ventastieneproductos vtp \n"
        r7 = "      WHERE v.idventa=vtp.idticket \n"
        r8 = "            AND v.nrofactura=vtp.nrofactura \n"
        r9 = "            "+opcion2+opcion3+") AS p1 \n"
        r0 = "WHERE v.nrofactura=vtp.nrofactura AND v.idventa=vtp.idticket \n"
        rA = "      AND p1.idventa=v.idventa AND p1.nrofactura=vtp.nrofactura \n"
        rB = "      AND vtp.devuelto='1' "+opcion1
        rC = "GROUP BY v.sucursal "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB+rC
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        #print sql
        return datos

    def armarSQL5(self,sucursal):
        #obteniendo Ventas - totales
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"
        opcion2 = " AND v.sucursal='"+str(sucursal+1)+"' "
        opcion3 = " AND v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' "
            
        r1 = "SELECT v.sucursal,SUM(vtp.preciofinal) AS total,\n"
        r2 = "       (SUM(vtp.preciofinal)/1.21) AS iva,\n"
        r3 = "       (SUM(vtp.preciofinal)-SUM(vtp.preciofinal)/1.21) AS subtotal \n"
        r4 = "FROM ventas v, ventastieneproductos vtp, \n"
        r5 = "     (SELECT v.idventa, v.nrofactura \n"
        r6 = "      FROM ventas v, ventastieneproductos vtp \n"
        r7 = "      WHERE v.idventa=vtp.idticket \n"
        r8 = "            AND v.nrofactura=vtp.nrofactura \n"
        r9 = "            AND vtp.cantidad>0 "+opcion2+opcion3+") AS p1 \n"
        r0 = "WHERE v.nrofactura=vtp.nrofactura AND v.idventa=vtp.idticket \n"
        rA = "      AND p1.idventa=v.idventa AND p1.nrofactura=vtp.nrofactura \n"
        rB = "      AND vtp.devuelto<>'1' "+opcion1
        rC = "GROUP BY v.sucursal "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB+rC
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        #print sql
        return datos

    def armarSQL6(self,sucursal):
        #obteniendo Devoluciones - totales
        fecha1,fecha2 = self.rangoFecha()
        if self.checkBox1.GetValue() and self.checkBox2.GetValue():
            opcion1 = "\n"
        elif self.checkBox1.GetValue():
            opcion1 = " AND v.idformaticket='1' \n"
        else:
            opcion1 = " AND v.idformaticket='2' \n"
        opcion2 = " AND v.sucursal='"+str(sucursal+1)+"' "
        opcion3 = " AND v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' "
        
        r1 = "SELECT v.sucursal,SUM(vtp.preciofinal) AS total,\n"
        r2 = "       (SUM(vtp.preciofinal)/1.21) AS iva,\n"
        r3 = "       (SUM(vtp.preciofinal)-SUM(vtp.preciofinal)/1.21) AS subtotal \n"
        r4 = "FROM ventas v, ventastieneproductos vtp, \n"
        r5 = "     (SELECT v.idventa, v.nrofactura \n"
        r6 = "      FROM ventas v, ventastieneproductos vtp \n"
        r7 = "      WHERE v.idventa=vtp.idticket \n"
        r8 = "            AND v.nrofactura=vtp.nrofactura \n"
        r9 = "            AND vtp.cantidad<0 "+opcion2+opcion3+") AS p1 \n"
        r0 = "WHERE v.nrofactura=vtp.nrofactura AND v.idventa=vtp.idticket \n"
        rA = "      AND p1.idventa=v.idventa AND p1.nrofactura=vtp.nrofactura \n"
        rB = "      AND vtp.devuelto<>'1' "+opcion1
        rC = "GROUP BY v.sucursal "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB+rC
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        #print sql
        return datos

    def armarSQL7(self,sucursal):
        #obteniendo Ventas - totales -> solo en 1 (buscamos IVA)
        fecha1,fecha2 = self.rangoFecha()
        opcion1 = " v.idformaticket='1' \n"
        opcion2 = " AND v.sucursal='"+str(sucursal+1)+"' "
        opcion3 = " AND v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' "
            
        r1 = "SELECT v.sucursal,SUM(v.totalsiniva) AS neto,\n"
        r2 = "       SUM(v.iva) AS iva,\n"
        r3 = "       SUM(v.totalfactura) AS total \n"
        r4 = "FROM ventas v \n"
        r5 = "WHERE "+opcion1+opcion2+opcion3
        r6 = "GROUP BY v.sucursal "
        sql = r1+r2+r3+r4+r5+r6
        datos,conecta = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
        
        return datos

    def determinarSucursales(self):
        sucursal=[]
        if self.comboBox1.GetSelection()==len(self.comboBox1.GetItems())-1:
            int = 0
            for item in self.comboBox1.GetItems():
                sucursal.append(int)
                int+= 1
            sucursal = sucursal[:-1]
        else:
            sucursal.append(self.comboBox1.GetSelection())
        return sucursal

    def reporte1Ventas(self,sucursal,fil):
        tSubtotal = Decimal("0.00")
        tIVA = Decimal("0.00")
        tTotal = Decimal("0.00")
        for sucu in sucursal:
            print "Buscando ventas:",
            dato = self.armarSQL5(sucu)
            try:
                subtotal = (dato[0]["subtotal"]).quantize(Decimal("0.10"))
            except:
                subtotal = Decimal("0.00")
            try:
                iva = (dato[0]["iva"]).quantize(Decimal("0.10"))
            except:
                iva = Decimal("0.00")
            try:
                total = (dato[0]["total"]).quantize(Decimal("0.10"))
            except:
                total = Decimal("0.00")
            tSubtotal+= subtotal
            tIVA+= iva
            tTotal+= total
            
            datoSucu = utiles.datosSucursal3(sucu+1)
            nombre = datoSucu[1]
            self.grid1.SetCellValue(fil,0,nombre)
            self.grid1.SetCellValue(fil,1,str(subtotal))
            self.grid1.SetCellValue(fil,2,str(iva))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1
        
        if len(sucursal)>1:
            self.grid1.SetCellValue(fil,0,"Total Vendido:")
            self.grid1.SetCellValue(fil,1,str(tSubtotal))
            self.grid1.SetCellValue(fil,2,str(tIVA))
            self.grid1.SetCellValue(fil,3,str(tTotal))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1
            
        return fil

    def reporte1NC(self,sucursal,fil):
        tSubtotal = Decimal("0.00")
        tIVA = Decimal("0.00")
        tTotal = Decimal("0.00")

        for sucu in sucursal:
            print "Buscando NC:",
            dato = self.armarSQL4(sucu)
            try:
                subtotal = (dato[0]["subtotal"]).quantize(Decimal("0.10"))
            except:
                subtotal = Decimal("0.00")
            try:
                iva = (dato[0]["iva"]).quantize(Decimal("0.10"))
            except:
                iva = Decimal("0.00")
            try:
                total = (dato[0]["total"]).quantize(Decimal("0.10"))
            except:
                total = Decimal("0.00")
            tSubtotal+= subtotal
            tIVA+= iva
            tTotal+= total
            
            datoSucu = utiles.datosSucursal3(sucu+1)
            nombre = datoSucu[1]
            self.grid1.SetCellValue(fil,0,nombre)
            self.grid1.SetCellValue(fil,1,str(subtotal))
            self.grid1.SetCellValue(fil,2,str(iva))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        if len(sucursal)>1:
            self.grid1.SetCellValue(fil,0,"Total N.C.:")
            self.grid1.SetCellValue(fil,1,str(tSubtotal))
            self.grid1.SetCellValue(fil,2,str(tIVA))
            self.grid1.SetCellValue(fil,3,str(tTotal))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        return fil

    def reporte1Devoluciones(self,sucursal,fil):
        tSubtotal = Decimal("0.00")
        tIVA = Decimal("0.00")
        tTotal = Decimal("0.00")

        for sucu in sucursal:
            print "Buscando Devoluciones:",
            dato = self.armarSQL6(sucu)
            try:
                subtotal = (dato[0]["subtotal"]).quantize(Decimal("0.10"))
            except:
                subtotal = Decimal("0.00")
            try:
                iva = (dato[0]["iva"]).quantize(Decimal("0.10"))
            except:
                iva = Decimal("0.00")
            try:
                total = (dato[0]["total"]).quantize(Decimal("0.10"))
            except:
                total = Decimal("0.00")
            tSubtotal+= subtotal
            tIVA+= iva
            tTotal+= total
            
            datoSucu = utiles.datosSucursal3(sucu+1)
            nombre = datoSucu[1]
            self.grid1.SetCellValue(fil,0,nombre)
            self.grid1.SetCellValue(fil,1,str(subtotal))
            self.grid1.SetCellValue(fil,2,str(iva))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        if len(sucursal)>1:
            self.grid1.SetCellValue(fil,0,"Total Devoluciones:")
            self.grid1.SetCellValue(fil,1,str(tSubtotal))
            self.grid1.SetCellValue(fil,2,str(tIVA))
            self.grid1.SetCellValue(fil,3,str(tTotal))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        return fil

    def reporteVentasIVA(self,sucursal,fil):
        tSubtotal = Decimal("0.00")
        tIVA = Decimal("0.00")
        tTotal = Decimal("0.00")
        for sucu in sucursal:
            print "Buscando ventas:",
            dato = self.armarSQL7(sucu)
            try:
                subtotal = (dato[0]["neto"]).quantize(Decimal("0.10"))
            except:
                subtotal = Decimal("0.00")
            try:
                iva = (dato[0]["iva"]).quantize(Decimal("0.10"))
            except:
                iva = Decimal("0.00")
            try:
                total = (dato[0]["total"]).quantize(Decimal("0.10"))
            except:
                total = Decimal("0.00")
            tSubtotal+= subtotal
            tIVA+= iva
            tTotal+= total
            
            datoSucu = utiles.datosSucursal3(sucu+1)
            nombre = datoSucu[1]
            self.grid1.SetCellValue(fil,0,nombre)
            self.grid1.SetCellValue(fil,1,str(subtotal))
            self.grid1.SetCellValue(fil,2,str(iva))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1
        
        if len(sucursal)>1:
            self.grid1.SetCellValue(fil,0,"Total General:")
            self.grid1.SetCellValue(fil,1,str(tSubtotal))
            self.grid1.SetCellValue(fil,2,str(tIVA))
            self.grid1.SetCellValue(fil,3,str(tTotal))
            self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1
            
        return fil

    def OnProcesar(self, event):
        if not self.verificarOpciones():
            return
        if self.comboBox2.GetSelection()==0: #Ventas, NC, Devoluciones
            self.reporte1()
        if self.comboBox2.GetSelection()==1: #Ventas 1, 2 y comisiones
            self.reporte2()
        if self.comboBox2.GetSelection()==2: #Ventas segun medios de pagos
            self.reporte3()
        if self.comboBox2.GetSelection()==3: #Listado de IVA
            self.reporte4()

    def reporte1(self):
        self.limpiarGrilla()
        columnas = ['Sucursal\nTipo Operacion','Subtotal','IVA','Total']
        for col,titulo in enumerate(columnas):
            self.grid1.AppendCols()
            self.grid1.SetColLabelValue(col,titulo)
        self.grid1.DeleteCols(self.grid1.GetNumberCols()-1)
        self.grid1.Refresh()
        sucursal = self.determinarSucursales()

        fil = 0
        fil = self.reporte1Ventas(sucursal,fil)
        fil = self.reporte1NC(sucursal,fil)
        fil = self.reporte1Devoluciones(sucursal,fil)

        print "Totalizando"
        tSubtotal = Decimal("0.00")
        tIVA = Decimal("0.00")
        tTotal = Decimal("0.00")
        for fila in xrange(self.grid1.GetNumberRows()):
            if self.grid1.GetCellValue(fila,0)=="": continue
            subtotal = Decimal(self.grid1.GetCellValue(fila,1))
            iva = Decimal(self.grid1.GetCellValue(fila,2))
            total = Decimal(self.grid1.GetCellValue(fila,3))
            tSubtotal+= subtotal
            tIVA+= iva
            tTotal+= total
        self.grid1.SetCellValue(fil,0,"TOTALES")
        self.grid1.SetCellValue(fil,1,str(tSubtotal))
        self.grid1.SetCellValue(fil,2,str(tIVA))
        self.grid1.SetCellValue(fil,3,str(tTotal))
        self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.ajustarAnchoColumnas()

    def sqlComisiones(self,sucursales):
        fecha1,fecha2 = self.rangoFecha()
        
        #ventas
        r01 = "SELECT SUM(v.totalfactura) AS ventas, vd.nombre \n"
        r02 = "FROM ventas v, vendedoras vd \n"
        r03 = "WHERE v.fecha BETWEEN '"+fecha1+" 00:00:00' AND '"+fecha2+" 23:59:59' \n"
        r04 = "      AND v.totalfactura >0 AND vd.idvendedora = v.usuario \n"
        r05 = "GROUP BY vd.nombre ORDER BY SUM( v.totalfactura ) DESC "
        sql = r01+r02+r03+r04+r05
        vendedoras = {}
        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                nc = 0
                for item in resultado:
                    nombre = item["nombre"]
                    ventas = item["ventas"]
                    try:
                        vtas,nc = vendedoras[(nombre,sucursal)]
                        vtas+= ventas
                        vendedoras[(nombre,sucursal)] = (vtas,nc)
                    except:
                        vendedoras[(nombre,sucursal)] = (ventas,0)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        #notas de creditos
        r01 = "SELECT vd.nombre, SUM(v.totalfactura) AS nc \n"
        r02 = "FROM ventas v, vendedoras vd \n"
        r03 = "WHERE v.usuario = vd.idvendedora AND v.totalfactura <0 \n"
        r04 = "      AND fecha BETWEEN '"+fecha1+" 00:00:00' \n"
        r05 = "      AND '"+fecha2+" 23:59:59' GROUP BY v.usuario \n"
        r06 = "ORDER BY nc DESC "
        sql = r01+r02+r03+r04+r05+r06

        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                for item in resultado:
                    nombre = item["nombre"]
                    nc = item["nc"]
                    try:
                        vtas,ncto = vendedoras[(nombre,sucursal)]
                        ncto+= nc
                        vendedoras[(nombre,sucursal)] = (vtas,ncto)
                    except:
                        vendedoras[(nombre,sucursal)] = (0,nc)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        totalizador = {}
        for item in vendedoras:
            nombre,sucursal = item
            ventas,nc = vendedoras[(nombre,sucursal)]
            try:
                vtasTotal,ncTotal = totalizador[nombre]
                vtasTotal+= ventas
                ncTotal+= nc
                totalizador[nombre] = (vtasTotal,ncTotal)
            except:
                totalizador[nombre] = (ventas,nc)

        return totalizador,vendedoras

    def sqlVentasDelPeriodo12comisiones(self,sucursales):
        fecha1,fecha2 = self.rangoFecha()
        
        #ventas tipo 1
        r1 = "SELECT SUM( totalfactura ) AS total FROM ventas "
        r2 = "WHERE fecha BETWEEN '"+fecha1+" 00:00:00' "
        r3 = "      AND '"+fecha2+" 23:59:59' AND idformaticket='1' "
        r4 = "      AND totalfactura>0 "
        sql = r1+r2+r3+r4
        
        vendido = {}
        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                for item in resultado:
                    ventas = item["total"]
                    try:
                        en1,en2,aux = vendido[sucursal]
                        en1+= ventas
                        vendido[sucursal] = (en1,en2,en1+en2)
                    except:
                        vendido[sucursal] = (ventas,0,ventas)
            else:
                print "Sin comunicacion con sucursal",sucursal+1
        
        #ventas tipo 2
        r1 = "SELECT SUM( totalfactura ) AS total FROM ventas "
        r2 = "WHERE fecha BETWEEN '"+fecha1+" 00:00:00' "
        r3 = "      AND '"+fecha2+" 23:59:59' AND idformaticket='2' "
        r4 = "      AND totalfactura>0 "
        sql = r1+r2+r3+r4
        
        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                for item in resultado:
                    ventas = item["total"]
                    try:
                        en1,en2,aux = vendido[sucursal]
                        en2+= ventas
                        vendido[sucursal] = (en1,en2,en1+en2)
                    except:
                        vendido[sucursal] = (0,ventas,ventas)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        fecha = fecha1[:4]+fecha1[5:7]
        for sucursal in sucursales:
            r1 = "SELECT objetivo1,objetivo2 FROM objetivos "
            r2 = "WHERE fecha='"+fecha+"' AND sucursal='"+str(sucursal+1)+"' "
            sql = r1+r2
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                obj1 = resultado[0]["objetivo1"]
                obj2 = resultado[0]["objetivo2"]
                try:
                    en1,en2,tot = vendido[sucursal]
                    vendido[sucursal] = (en1,en2,tot,obj1,obj2)
                except:
                    vendido[sucursal] = (0,0,0,obj1,obj2)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        #obtencion de N.C. en 1
        r1 = "SELECT SUM( totalfactura ) AS total FROM ventas "
        r2 = "WHERE fecha BETWEEN '"+fecha1+" 00:00:00' "
        r3 = "      AND '"+fecha2+" 23:59:59' AND idformaticket='1' "
        r4 = "      AND totalfactura<0 "
        sql = r1+r2+r3+r4
        
        notascredito = {}
        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                for item in resultado:
                    nc1 = item["total"]
                    if nc1 is None: nc1 = Decimal("0.00")
                    try:
                        en1,en2 = adicionales[sucursal]
                        en1+= nc1
                        notascredito[sucursal] = (en1,en2)
                    except:
                        notascredito[sucursal] = (nc1,0)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        #obtencion de N.C. en 2
        r1 = "SELECT SUM( totalfactura ) AS total FROM ventas "
        r2 = "WHERE fecha BETWEEN '"+fecha1+" 00:00:00' "
        r3 = "      AND '"+fecha2+" 23:59:59' AND idformaticket='2' "
        r4 = "      AND totalfactura<0 "
        sql = r1+r2+r3+r4
        
        for sucursal in sucursales:
            resultado,conexion = consultasBD.ordenCrudaDictRemota2(sql,sucursal)
            if conexion:
                for item in resultado:
                    nc2 = item["total"]
                    if nc2 is None: nc2 = Decimal("0.00")
                    try:
                        en1,en2 = notascredito[sucursal]
                        en2+= nc2
                        notascredito[sucursal] = (en1,en2)
                    except:
                        notascredito[sucursal] = (0,nc2)
            else:
                print "Sin comunicacion con sucursal",sucursal+1

        return vendido,notascredito

    def reporte2(self):
        self.limpiarGrilla()
        columnas = ['Sucursal','Ventas 1','Ventas 2','Total',\
                    'Objetivo 1','Objetivo 2']
        for col,titulo in enumerate(columnas):
            self.grid1.AppendCols()
            self.grid1.SetColLabelValue(col,titulo)
        self.grid1.DeleteCols(self.grid1.GetNumberCols()-1)
        self.grid1.Refresh()
        sucursal = self.determinarSucursales()
        vendido,notascredito = self.sqlVentasDelPeriodo12comisiones(sucursal)
        totalizador,vendedoras = self.sqlComisiones(sucursal)

        fil = 0
        for item in vendido:
            sucursal = item
            en1,en2,total,obj1,obj2 = vendido[sucursal]
            datos = utiles.datosSucursal3(sucursal+1)
            self.grid1.SetCellValue(fil,0,datos[1])
            self.grid1.SetCellValue(fil,1,str(en1))
            self.grid1.SetCellValue(fil,2,str(en2))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellValue(fil,4,str(obj1))
            self.grid1.SetCellValue(fil,5,str(obj2))

            self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        self.grid1.SetCellValue(fil,0,"TOTAL")
        tot1 = Decimal("0.00")
        tot2 = Decimal("0.00")
        totG = Decimal("0.00")
        for fila in xrange(self.grid1.GetNumberRows()):
            try:
                aux1 = Decimal(self.grid1.GetCellValue(fila,1))
            except:
                aux1 = Decimal("0.00")
            try:
                aux2 = Decimal(self.grid1.GetCellValue(fila,2))
            except:
                aux2 = Decimal("0.00")
            try:
                aux3 = Decimal(self.grid1.GetCellValue(fila,3))
            except:
                aux3 = Decimal("0.00")
            tot1+= aux1
            tot2+= aux2
            totG+= aux3
        self.grid1.SetCellValue(fil,1,str(tot1.quantize(Decimal("0.10"))))
        self.grid1.SetCellValue(fil,2,str(tot2.quantize(Decimal("0.10"))))
        self.grid1.SetCellValue(fil,3,str(totG.quantize(Decimal("0.10"))))
        self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.AppendRows()
        fil+= 1
        self.grid1.AppendRows()
        fil+= 1
        
        filainicio = fil
        self.grid1.SetCellValue(fil,0,"Vendedora")
        self.grid1.SetCellValue(fil,1,"Ventas")
        self.grid1.SetCellValue(fil,2,"N.C.")
        self.grid1.SetCellBackgroundColour(fil,0,GRIS)
        self.grid1.SetCellBackgroundColour(fil,1,GRIS)
        self.grid1.SetCellBackgroundColour(fil,2,GRIS)
        self.grid1.AppendRows()
        fil+= 1
        
        for item in totalizador:
            vendedor = item
            venta,nc = totalizador[vendedor]
            self.grid1.SetCellValue(fil,0,vendedor)
            self.grid1.SetCellValue(fil,1,str(venta))
            self.grid1.SetCellValue(fil,2,str(nc))
            self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1
            
        self.grid1.SetCellValue(fil,0,"TOTAL")
        tot1 = Decimal("0.00")
        tot2 = Decimal("0.00")
        for fila in xrange(self.grid1.GetNumberRows()):
            if fila < filainicio: continue
            try:
                aux1 = Decimal(self.grid1.GetCellValue(fila,1))
            except:
                aux1 = Decimal("0.00")
            try:
                aux2 = Decimal(self.grid1.GetCellValue(fila,2))
            except:
                aux2 = Decimal("0.00")
            tot1+= aux1
            tot2+= aux2
        self.grid1.SetCellValue(fil,1,str(tot1.quantize(Decimal("0.10"))))
        self.grid1.SetCellValue(fil,2,str(tot2.quantize(Decimal("0.10"))))
        self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.AppendRows()
        self.grid1.AppendRows()
        fil+= 2

        self.grid1.SetCellValue(fil,0,"VENTAS 1")
        self.grid1.AppendRows()
        fil+= 1

        self.grid1.SetCellValue(fil,0,"Sucursal")
        self.grid1.SetCellValue(fil,1,"Ventas")
        self.grid1.SetCellValue(fil,2,"N.C.")
        self.grid1.SetCellValue(fil,3,"Subtotal")
        self.grid1.SetCellValue(fil,4,"IVA")
        self.grid1.SetCellValue(fil,5,"TOTAL")
        self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 4, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 5, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellBackgroundColour(fil,0,GRIS)
        self.grid1.SetCellBackgroundColour(fil,1,GRIS)
        self.grid1.SetCellBackgroundColour(fil,2,GRIS)
        self.grid1.SetCellBackgroundColour(fil,3,GRIS)
        self.grid1.SetCellBackgroundColour(fil,4,GRIS)
        self.grid1.SetCellBackgroundColour(fil,5,GRIS)
        self.grid1.AppendRows()
        fil+= 1

        for item in vendido:
            sucursal = item
            en1,en2,total,obj1,obj2 = vendido[sucursal]
            try:
                nc1,nc2 = notascredito[sucursal]
            except:
                nc1,nc2 = (Decimal("0.00"),Decimal("0.00"))

            datos = utiles.datosSucursal3(sucursal+1)[1]
            totalVentas = (en1/Decimal("1.21")).quantize(Decimal("0.10"))
            totalNC = (nc1/Decimal("1.21")).quantize(Decimal("0.10"))
            subtotal = (totalVentas+totalNC).quantize(Decimal("0.10"))
            IVA = (en1-totalVentas+nc1-totalNC).quantize(Decimal("0.10"))
            total = (subtotal+IVA).quantize(Decimal("0.10"))

            #sucursal,ventas,nc,subtotal,IVA,total
            self.grid1.SetCellValue(fil,0,datos)
            self.grid1.SetCellValue(fil,1,str(totalVentas))
            self.grid1.SetCellValue(fil,2,str(totalNC))
            self.grid1.SetCellValue(fil,3,str(subtotal))
            self.grid1.SetCellValue(fil,4,str(IVA))
            self.grid1.SetCellValue(fil,5,str(total))
            self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        self.grid1.AppendRows()
        fil+= 1

        self.grid1.SetCellValue(fil,0,"VENTAS 2")
        self.grid1.AppendRows()
        fil+= 1

        self.grid1.SetCellValue(fil,0,"Sucursal")
        self.grid1.SetCellValue(fil,1,"Ventas")
        self.grid1.SetCellValue(fil,2,"N.C.")
        self.grid1.SetCellValue(fil,3,"TOTAL")
        self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.grid1.SetCellBackgroundColour(fil,0,GRIS)
        self.grid1.SetCellBackgroundColour(fil,1,GRIS)
        self.grid1.SetCellBackgroundColour(fil,2,GRIS)
        self.grid1.SetCellBackgroundColour(fil,3,GRIS)
        self.grid1.AppendRows()
        fil+= 1

        for item in vendido:
            sucursal = item
            en1,en2,total,obj1,obj2 = vendido[sucursal]
            try:
                nc1,nc2 = notascredito[sucursal]
            except:
                nc1,nc2 = (Decimal("0.00"),Decimal("0.00"))

            datos = utiles.datosSucursal3(sucursal+1)[1]
            totalVentas = en2.quantize(Decimal("0.10"))
            totalNC = nc2.quantize(Decimal("0.10"))
            total = (totalVentas+totalNC).quantize(Decimal("0.10"))

            #sucursal,ventas,nc,total
            self.grid1.SetCellValue(fil,0,datos)
            self.grid1.SetCellValue(fil,1,str(totalVentas))
            self.grid1.SetCellValue(fil,2,str(totalNC))
            self.grid1.SetCellValue(fil,3,str(total))
            self.grid1.SetCellAlignment(fil, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fil, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fil+= 1

        self.ajustarAnchoColumnas()
        
    def OnImprimir(self, event):
        print "Imprimiendo"
        
        f=open("c:\\matrisamor.doc\\reporte-ReporteVentas2.html","w")
        numeroPagina = 1
        nrosuc,nombresuc = utiles.datosSucursal()
        
        totalItemPorPagina = 50
        totalPaginas = int(self.grid1.GetNumberRows()-1) / totalItemPorPagina 
        totalPaginas+= 1

        def encabezadoPagina(texto):
            fecha = utiles.getfechaTime()
            
            fecha1 = self.datePickerCtrl1.GetLabel()
            fecha2 = self.datePickerCtrl2.GetLabel()

            a = '<table width="100%" cellspacing="0" border="0">\n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left" width="33%">'
            a+= 'SUSSAN BOUTIQUE<br>Ventas por Per&iacute;odos'
            a+= '</td>\n'
            a+= '<td valign="top" align="left" width="34%">Desde '+fecha1
            a+= '<br>Hasta '+fecha2
            if self.grid1.GetColLabelValue(4)=="Objetivo 1":
                a+='<br>D&iacute;as pendientes: '+self.textCtrl3.GetLabel()
            a+= '</td>\n'
            a+= '<td valign="top" align="right" width="33%">'+fecha
            a+= '<br>P&aacute;gina '+str(numeroPagina)+' / '+str(totalPaginas)+'</td>\n'
            a+= '</tr>\n'
            a+= '</table>\n'
            texto+= a
            return texto
        
        def encabezadoTabla(texto):
            #idfactura,Proveedor,Nro.Factura,F.Factura,F.Ingreso,Cant,Tipo,Subtotal,IVA,Total
            #0         1         2           3         4         5    6    7        8   9
            a = '<hr>'
            tama = '"2"'
            a+= '<table width="100%" cellspacing="1" border="0"> \n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="right"><font size='+tama+'>Orden</font></td> \n'
            for col in xrange(self.grid1.GetNumberCols()):
                titulo = self.grid1.GetColLabelValue(col)
                titulo = titulo.replace("\n","<br>")
                a+= '<td valign="top" align="right"><font size='+tama+'>'+titulo+'</font></td> \n'
            a+= '</tr> \n'
            a+= '<tr>\n'
            a+= '<td colspan="'+str(self.grid1.GetNumberCols()+1)+'"><hr></td>\n'
            a+= '</tr>\n'
            texto+= a
            return texto
        
        cadena = '<?xml version="1.0" encoding="utf-8" ?> \n'
        cadena+= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> \n'
        cadena+= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> \n'
        cadena+= '<head> \n'
        cadena+= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> \n'
        cadena+= '<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" /> \n'
        cadena+= '<title>Sussan Boutique</title> \n'
        cadena+= '</head> \n'
        cadena+= '<body> \n'

        cadena = encabezadoPagina(cadena)
        cadena = encabezadoTabla(cadena)
        f.write(cadena)
        
        renglon = 0
        orden = 0
        for fil in xrange(self.grid1.GetNumberRows()):
            if self.grid1.GetCellValue(fil,0)=="": 
                cadena = '<tr> \n'
                cadena+= '<td colspan="'+str(self.grid1.GetNumberCols()+1)+'"></td> \n'
                cadena+= '</tr>\n'
            else:
                orden+= 1
                tama = '"0.02"'
                cadena = '<tr> \n'
                cadena+= '<td valign="top" align="right"><font size='+tama+'>'+str(orden)+'</font></td> \n'
                for col in xrange(self.grid1.GetNumberCols()):
                    valor = self.grid1.GetCellValue(fil,col)
                    cadena+= '<td valign="top" align="right"><font size='+tama+'>'+valor+'</font></td> \n'
                cadena+= '</font></tr>\n'
            f.write(cadena)
            
            renglon+= 1
            
            if renglon == totalItemPorPagina :
                renglon = 0
                numeroPagina+= 1
                cadena = encabezadoPagina("")
                cadena = encabezadoTabla(cadena)
                f.write(cadena)

        cadena = '</table>\n'
        cadena+= '</body>\n</html>\n'
        f.write(cadena)
        f.close()

        import os
        os.system("taskkill /IM firefox.exe /F")
        os.system("c:\\explorer.lnk c:\\matrisamor.doc\\reporte-ReporteVentas2.html")

    def reporte3(self):
        pass
    
    def reporte4(self):
        self.limpiarGrilla()
        columnas = ['Sucursal','neto','IVA','Total']
        for col,titulo in enumerate(columnas):
            self.grid1.AppendCols()
            self.grid1.SetColLabelValue(col,titulo)
        self.grid1.DeleteCols(self.grid1.GetNumberCols()-1)
        self.grid1.Refresh()
    
        sucursal = self.determinarSucursales()

        fil = 0
        fil = self.reporteVentasIVA(sucursal,fil)

##        print "Totalizando"
##        tSubtotal = Decimal("0.00")
##        tIVA = Decimal("0.00")
##        tTotal = Decimal("0.00")
##        for fila in xrange(self.grid1.GetNumberRows()):
##            if self.grid1.GetCellValue(fila,0)=="": continue
##            subtotal = Decimal(self.grid1.GetCellValue(fila,1))
##            iva = Decimal(self.grid1.GetCellValue(fila,2))
##            total = Decimal(self.grid1.GetCellValue(fila,3))
##            tSubtotal+= subtotal
##            tIVA+= iva
##            tTotal+= total
##        self.grid1.SetCellValue(fil,0,"TOTALES")
##        self.grid1.SetCellValue(fil,1,str(tSubtotal))
##        self.grid1.SetCellValue(fil,2,str(tIVA))
##        self.grid1.SetCellValue(fil,3,str(tTotal))
##        self.grid1.SetCellAlignment(fil,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
##        self.grid1.SetCellAlignment(fil,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
##        self.grid1.SetCellAlignment(fil,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.ajustarAnchoColumnas()
    
    
